package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    @Transactional
    public Orders submit(Orders order) {
        long userId = BaseContext.getCurrentId();
        //校验购物车是否为空
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> cartList = shoppingCartService.list(wrapper);

        if (cartList == null || cartList.size() == 0){
            throw new CustomException("下单失败,购物车无信息!");
        }

        //校验收货人信息是否有效
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());

        if(addressBook == null){
            throw new CustomException("下单失败,无收货地址信息!");
        }

        //拿到当前用户信息
        User user = userService.getById(BaseContext.getCurrentId());

        //1. 添加订单数据
        //1.1 封装订单数据
        long orderId = IdWorker.getId();
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setUserName(user.getName());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getCityName()+","+addressBook.getDistrictName()+","+addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setCheckoutTime(LocalDateTime.now());

        //1.2 计算订单总价
        AtomicInteger amount = new AtomicInteger(0);
        cartList.stream().forEach(item->{
            //获取商品单价
            BigDecimal dj = item.getAmount();
            //获取商品数量
            Integer count = item.getNumber();
            //计算商品总价,并累加到总价上
            amount.getAndAdd(dj.multiply(new BigDecimal(count.toString())).intValue());
        });
        order.setAmount(new BigDecimal(amount.get()));
        //1.3 新增订单
        this.save(order);

        //2. 添加订单详情数据
        List<OrderDetail> details = cartList.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            orderDetail.setImage(item.getImage());
            return orderDetail;
        }).collect(Collectors.toList());
        //2.1 批量保存订单详情
        orderDetailService.saveBatch(details);

        //3. 清空购物车
        shoppingCartService.remove(wrapper);

        return order;
    }
}
